var menuTemplate = '<li class="menuItem menu textList"></li>';
var menus = {};
var mySubMenus = {};
var myMenu = {};
var lastSubRowIds = {};

$().ready(function(){
	$('.batterieSelectionForm').submit(sendBatteriesForMenu);
	loadMyMenu();
});

function displayMenuManagement() {
	hideContainers();
	loadAvailableMenus();
	$.each(batteries, fillBatterieForMenu);
	showContainer('menuManagement');
}

function fillBatterieForMenu(idx, batterie) {
	var batterieDom = $('<li />');
	batterieDom.append($('<input type="checkbox" name="bat" class="checkbox">').val(idx).attr('id', 'batMenu' + idx));
	batterieDom.append($('<label/>').html(batterie.nom).attr('for', 'batMenu' + idx));
	$('.container.menuManagement .batterieSelectionContainer').append(batterieDom);
}

function loadAvailableMenus() {
	$('.container.menuManagement .menus.public .data').html('');
	
	$.getJSON(serverPath + '/mainmenu/list', function(data) {
		menus = data;
		menus.push({id:'private', nom:'Menu personnalisé'});
		
		$.each(menus, function(idx, menu){
			var menuDom = $(menuTemplate);
			menuDom.addClass('menu_' + menu.id).html($('<a/>').html(menu.nom).attr('href', '#').click(
				function(){
					$.ajax({
						type: 'POST',
						url: serverPath + '/mainmenu/put/',
						data: {id: menu.id},
						success: function(exercice) {
							$('.container.menuManagement .menus.public li').removeClass('selected');
							$('.container.menuManagement .menus.public .menu_' + menu.id).addClass('selected');
						},
						error: function(data) {
							displayPopup("Le menu n'a pas pu être mis à jour");
						},
						dataType: 'json'
					});
					return false;
				}
			));
			if ((menu.id == user.menu_id) || ((menu.id == 'private') && (user.menu_id == user.private_menu_id))){
				menuDom.addClass('selected');
			}
			$('.container.menuManagement .menus.public .data').append(menuDom);
		});
	});
	
	selectPublicMenu();
}

function loadMyMenu(callback) {
	if (batteries == null) {
		setTimeout(loadMyMenu, 200);
		return;
	}
	// get my menu
	$.ajax({
		type: 'GET',
		url: serverPath + '/mainmenu/get',
		data: {id: 'private'},
		success: function(myMenus) {
			myMenu = myMenus;
		    $('#privateGrid').jqGrid({
		        jsonReader:{repeatitems:false,subgrid:{repeatitems:false}},
		        caption: 'Menus',
		        gridview: true,
		        loadonce: true,
		        rowNum:100,
		        autowidth:true,
		        height: '100%',
		        sortname: 'sort_order',
		        rowList:[100,200,300],
		        datatype: 'local',
		        colNames: ['Id', '', 'Nom', 'Tri'],
		        colModel:[
		            {'name':'id','index':'id','sorttype':'int','key':true,'editable':false, 'hidden':true},
		            {width:24, 'name':'renommer','index':'renommer', 'formatter':renameMPFormatter, 'unformat': renameMPUnFormatter},
		            {width:408, 'name':'nom','index':'nom','classes':'ui-ellipsis','editable':true,sortable:false},
		            {'name':'sort_order','index':'sort_order','classes':'ui-ellipsis',sortable:false, 'hidden':true}
		        ],
		        subGridOptions: {
		        	plusicon : 'ui-icon-minus',
		        	minusicon : 'ui-icon-minus',
		        	openicon: 'ui-icon-carat-1-sw hidden', 
		        	expandOnLoad: false, 
		        	selectOnExpand : false, 
		        	reloadOnExpand : false 
		        },
		        subGrid: true,
		        subGridRowExpanded: function(subgrid_id, row_id) {
		               var subgrid_table_id;
		               subgrid_table_id = subgrid_id + "_t";
		               $('#'+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table>");
		               $('#'+subgrid_table_id).jqGrid({
							jsonReader:{repeatitems:false,subgrid:{repeatitems:false}},
					        caption: 'Sous-Menus',
					        colNames: ['Id', '', 'Nom', 'Tri', 'Params', 'Batteries'],
							colModel: [
					            {'name':'id','index':'id','sorttype':'int','key':true,'editable':false, 'hidden':true,sortable:false},
					            {width:24, 'name':'renommer','index':'renommer', 'formatter':renameSMFormatter, 'unformat': renameSMUnFormatter},
					            {width:200, 'name':'nom','index':'nom','classes':'ui-ellipsis','editable':true,sortable:false},
					            {'name':'sort_order','index':'sort_order','classes':'ui-ellipsis',sortable:false, 'hidden':true},
			                    {'name':'params','index':'params',align:'right',sortable:false, 'hidden':true},
					            {width:200, 'name':'menu_principal_id', 'index':'menu_principal_id', classes:'ui-ellipsis menuBatContainer',align:'right',sortable:false, 'formatter':batFormatter, 'unformat': batUnformatter}
							],
							height: '100%',
							rowNum: 100,
							sortname: 'sort_order'
		               });
		   		    
		               var row = $("#privateGrid").jqGrid('getRowData', row_id);

		               // addind 'Add' button
		               $('#'+subgrid_id + ' .ui-jqgrid-titlebar').append(
			   	    		$('<a href="#" class="ui-jqgrid-titlebar-add"><span class="icon">+</span></a>').click(function(){
			   	    			addSubMenu(subgrid_table_id, row.id, row_id);
				    			return false;
			   	    		})
			   			);
		               
			   		    // adding submenus
		                if (typeof mySubMenus != 'undefined' && typeof mySubMenus[row.id] != 'undefined' && typeof mySubMenus[row.id].sousmenu != 'undefined') {
		                	$.each(mySubMenus[row.id].sousmenu, function(idx, submenu){
		                		lastSubRowIds[row_id] = idx;
		                		addSousMenuRow(subgrid_table_id, submenu, row_id);
		                	});
		                }
			   			
			   			return true;
		          }
		    });
		    
		    // addind 'Add' button
		    $('.privateMenu .ui-jqgrid-titlebar').append(
	    		$('<a href="#" class="ui-jqgrid-titlebar-add"><span class="icon">+</span></a>').click(function(){
	    			addMenuPrincipal();
	    			return false;
	    		})
			);

		    // adding data
			$.each(myMenus, function(idx, menu){
				lastRowId = idx;
				addMenuPrincipalRow(menu);
			});
			
			if (typeof callback !== 'undefined') {
				callback();
			}
		},
		error: function(error) {
			if (error.status == 404){
				$('.container.menuManagement .resetMyMenu').addClass('hidden');
				$('.container.menuManagement .createMyMenu').removeClass('hidden');
				$('.container.menuManagement .notYet').removeClass('hidden');
				hideMyMenu();
			}else{
				displayPopup("Le menu n'a pas pu être mis à jour.");
			}
		},
		dataType: 'json'
	});
}

function renameMPFormatter(cellvalue, options, rowObject) {
	return $('<div />').append($("<a href='#' onclick='renameMenuPrincipal(\"" + options.rowId + "\");return false;' title='Renommer le menu' class='editCell'></a>")).html();
}
function renameMPUnFormatter( cellvalue, options, cell){
	return '';
}

function renameSMFormatter(cellvalue, options, rowObject) {
	return $('<div />').append($("<a href='#' onclick='renameSousMenu(\"" + options.rowId + "\");return false;' title='Renommer le menu' class='editCell'></a>")).html();
}
function renameSMUnFormatter( cellvalue, options, cell){
	return '';
}

function batFormatter(cellvalue, options, rowObject) {
	return $('<div />').append(menuBatListBuilder(rowObject)).append($("<button onclick='modifyMenuBatteries(\"" + cellvalue + "\", \"" + rowObject.id + "\", \"" + options.rowId + "\")' title='Modifier la liste des batteries'>...</button>")).html();
}
function batUnformatter( cellvalue, options, cell){
	return '';
}

function hideMyMenu() {
	if ($('.container.menuManagement .menuItem.menu_private').exists()) {
		$('.container.menuManagement .menuItem.menu_private').addClass('hidden');
	}else{
		setTimeout(hideMyMenu, 200);
	}
}

function menuBatListBuilder(subMenu) {
	var batIds = subMenu.params.replace(/.*ids=([0-9,]*).*/g,'$1');
	var list = $('<ul class="menuBatContainer"/>');
	if (batIds != "") {
		batIds = batIds.split(',');
		for ( var i = 0; i < batIds.length; i++) {
			if (typeof batteries[batIds[i]] !== 'undefined') {
				list.append($('<li />').html(batteries[batIds[i]].nom).attr('title', batteries[batIds[i]].nom));
			}
		}
	}
	return list;
}

function modifyMenuBatteries(menuPrincipalId, submenuId, rowId) {
	var menuP = mySubMenus[menuPrincipalId];
	var subM = null;
	if (typeof menuP === 'undefined') {
		return;
	}
	for (var i = 0;i<menuP.sousmenu.length;i++) {
		if ((menuP.sousmenu)[i].id == submenuId) {
			subM = (menuP.sousmenu)[i];
		}
	}
	if (subM == null) {
		return;
	}
	
	currentSelectedSubMenuId = rowId;

	var batIds = (subM.params.indexOf('ids=') > -1) ? subM.params.replace(/.*ids=([0-9,]*).*/g,'$1').split(',') : [];	
	$('.batterieSelectionForm input').removeAttr('checked');
	for (var i = 0;i<batIds.length;i++) {
		$('.batterieSelectionForm input[value=' + batIds[i] +']').attr('checked', 'checked');
	}
	$('.batterieSelectionForm input[name=subMenuId]').val(submenuId);
	
	$('.batterieSelectionForm .title').html(subM.nom);
	$('.batterieSelectionForm').removeClass('hidden');
}

function sendBatteriesForMenu() {
	var bats = '';
	$('.batterieSelectionForm input[name=bat]:checked').each(function(i, inp){
		if (bats != '') {bats+=',';}
		bats += $(inp).val();
	});
	$.ajax({
		type: 'POST',
		url: serverPath + '/sousmenu/put/',
		data: {
				subMenuId: $('.batterieSelectionForm input[name=subMenuId]').val(),
				batteries: bats
			},
		success: function(data) {
			$('.batterieSelectionForm').addClass('hidden');
			var list = menuBatListBuilder(data);
			$('#' + currentSelectedSubMenuId + ' .menuBatContainer ul').remove();
			$('#' + currentSelectedSubMenuId + ' .menuBatContainer').prepend(list);
		},
		error: function(error) {
			displayPopup("Le menu n'a pas pu être mis à jour.");
		},
		dataType: 'json'
	});
	return false;
}

function addMenuPrincipal(rowId) {
	var name = prompt('Veuillez inscrire le nom du nouveau menu principal.','');
	if (name == null || '' == name){
		return;
	}
	
	$.ajax({
		type: 'POST',
		url: serverPath + '/menuprincipal/post/',
		data: {nom: name},
		success: function(menu) {
			lastRowId++;
			addMenuPrincipalRow(menu);
		},
		error: function(error) {
			displayPopup("Le menu n'a pas pu être créé.");
		},
		dataType: 'json'
	});
	
	return false;
}

function addMenuPrincipalRow(menu) {
	mySubMenus[menu.id] = menu;
	var currentId = 'private_' + lastRowId;
	lastSubRowIds[currentId] = 0;
	$("#privateGrid").jqGrid('addRowData', currentId, menu);
	try {
		$("#privateGrid").expandSubGridRow(currentId);
	}catch(e) {
		//OK
	}
	$('#' + currentId).children('td.ui-sgcollapsed').attr('title', 'Supprimer').unbind().bind('click', function(){deleteMenuPrincipal(menu.id, currentId);});
}
function renameMenuPrincipal(rowId) {
    var row = $("#privateGrid").jqGrid('getRowData', rowId);

	var name = prompt('Veuillez inscrire un nouveau nom pour ce menu.', row.nom);
	if (name == null || '' == name){
		return;
	}
	
	$.ajax({
		type: 'POST',
		url: serverPath + '/menuprincipal/rename/',
		data: {
				id: row.id,
				nom: name
			},
		success: function(data) {
			$("#privateGrid").jqGrid('setCell', rowId, 'nom', data.nom);
			$("#privateGrid").jqGrid('getLocalRow', rowId).nom = data.nom;
		},
		error: function(error) {
			displayPopup("Le menu n'a pas pu être mis à jour.");
		},
		dataType: 'json'
	});
}
function renameSousMenu(rowId) {
	var rowIdArr = rowId.split('_');
	var mainRowId = rowIdArr[1];
	var subGridId = "privateGrid_private_" + mainRowId + "_t";
	var row = $("#" + subGridId).jqGrid('getRowData', rowId);

	var name = prompt('Veuillez inscrire un nouveau nom pour ce sous-menu.', row.nom);
	if (name == null || '' == name){
		return;
	}
	
	$.ajax({
		type: 'POST',
		url: serverPath + '/sousmenu/rename/',
		data: {
				id: row.id,
				nom: name
			},
		success: function(data) {
			$("#" + subGridId).jqGrid('setCell', rowId, 'nom', data.nom);
			$("#" + subGridId).jqGrid('getLocalRow', rowId).nom = data.nom;
		},
		error: function(error) {
			displayPopup("Le sous-menu n'a pas pu être mis à jour.");
		},
		dataType: 'json'
	});
}

function deleteMenuPrincipal(menuPrincipalId, rowId) {
	$.ajax({
		type: 'POST',
		data: {id: menuPrincipalId},
		url: serverPath + '/menuprincipal/delete/',
		success: function(data) {
			var selRow = $('#' + rowId),
		    	nextRow = selRow.next();

			// delete subgrid
			if (nextRow.hasClass('ui-subgrid')) {
			    nextRow.remove();
			}
			$('#privateGrid').jqGrid('delRowData', rowId);
		},
		error: function(error) {
			displayPopup("Le menu n'a pas pu être supprimé.");
		},
		dataType: 'json'
	});
}

function addSubMenu(subgridTableid, menuPrincipalId, rowId) {
	var name = prompt('Veuillez inscrire le nom du nouveau sous-menu.', '');
	if (name == null || '' == name){
		return;
	}
	
	$.ajax({
		type: 'POST',
		url: serverPath + '/sousmenu/post/',
		data: {nom: name, menu_principal_id: menuPrincipalId},
		success: function(menu) {
			lastSubRowIds[rowId]++;
			if (typeof mySubMenus[menuPrincipalId].sousmenu == 'undefined') {
				mySubMenus[menuPrincipalId].sousmenu = []; 
			}
			mySubMenus[menuPrincipalId].sousmenu.push(menu);
			addSousMenuRow(subgridTableid, menu, rowId);
		},
		error: function(error) {
			displayPopup("Le menu n'a pas pu être créé.");
		},
		dataType: 'json'
	});
	
	return false;
}
function addSousMenuRow(subgridTableid, subMenu, rowId) {
	$('#'+subgridTableid).jqGrid('addRowData', rowId + '_' + lastSubRowIds[rowId], subMenu);
}

function resetMyMenu() {
	$.ajax({
		type: 'POST',
		url: serverPath + '/mainmenu/post/',
		data: {reset: '1'},
		success: function(data) {
			user.private_menu_id = data.id;
			$('.container.menuManagement .resetMyMenu').removeClass('hidden');
			$('.container.menuManagement .createMyMenu').addClass('hidden');
			$('.container.menuManagement .notYet').addClass('hidden');
			$('.container.menuManagement .menuItem.menu_private').removeClass('hidden');
			
			$('.container.menuManagement .menus.private').addClass('hidden');
            $("#privateGrid").jqGrid('GridUnload');
			loadMyMenu(selectPrivateMenu);
		},
		error: function(error) {
			displayPopup("Le menu n'a pas pu être réinitialisé.");
		},
		dataType: 'json'
	});
}

function selectPublicMenu() {
	$('.container.menuManagement .menus.public').removeClass('hidden');
	$('.container.menuManagement .menus.private').addClass('hidden');
}
function selectPrivateMenu() {
	$('.container.menuManagement .menus.public').addClass('hidden');
	$('.container.menuManagement .menus.private').removeClass('hidden');
}